<template>
  <div class="c-flex-grow1 c-w0 c-bg-white c-flex-row c-aligni-center c-hh80 c-pl24">
    <i class="iconfont c-fs28 c-fc-sgray">&#xe6d6;</i>
    <div @click="clickFocus" class="c-pl16 c-hh60 c-flex-row c-flex-grow1 c-w0 c-aligni-center c-fs28 c-bg-white">
      <form action="javascript:true;">
        <input
          ref="input"
          class="c-ww270 fs28"
          @focus="inputFocus"
          @blur="inputBlur"
          v-model="searchValue"
          :placeholder="placeholderText"
          type="search"
          @keyup.enter="clickSearch"
        >
      </form>
    </div>
    <div v-if="isFocus" class="c-pl24 c-fs28 c-fc-xblue" @click="clickCancelSearch">取消</div>
  </div>
</template>
<script>
let inputScrollTop = 0;
export default {
  name: "searchInputBar",
  props: {
    placeholderText: {
      type: String,
      default: "搜索"
    },
    searchText: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      searchValue: "",
      isFocus: false,
      searchKey: ""
    };
  },
  watch: {
    searchText(val) {
      this.searchValue = val;
    },
    searchValue(val) {
      this.searchValue = val;
      if (this.searchValue == "") {
        this.$emit("emptyInput");
      }
    }
  },
  methods: {
    clickFocus() {
      this.$refs.input.focus();
    },
    inputFocus() {
      this.isFocus = true;
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      this.isFocus = false;
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    clickCancelSearch() {
      this.searchValue = "";
      this.$emit("cancelSearch", this.searchValue);
    },
    clickSearch(e) {
      this.$emit("startSearch", this.searchValue);
      e.target.blur();
    }
  },
  activated() {
    this.isFocus = false;
    let search = sessionStorage.getItem("search");
    if (!!search) {
      this.searchValue = search;
      return;
    }
    this.searchValue = "";
  }
};
</script>

<style scoped>
input {
  font-size: 0.65rem;
  border: 0;
  background: none;
  outline: none;
}
input:focus {
  outline: none;
}
input[type="search"] {
  -webkit-appearance: textfield;
  -webkit-box-sizing: content-box;
}
input::-webkit-search-decoration,
input::-webkit-search-cancel-button {
  display: none;
}
</style>
